import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { compareDataField } from 'src/app/common/tools/condition-tool';
import { Condition } from 'src/app/models/condition';
import { PermitConfig, PermitConfigId } from '../../../models';
import { BaseFieldComponent } from '../base-field/base-field.component';

@Component({
  selector: 'zepride-tabs',
  templateUrl: './tabs.component.html',
  styleUrls: ['./tabs.component.less', '../field.common.less']
})
export class TabsComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  tabItemConfigs: ITabItemConfig[] = [];
  get disTabConfigs() {
    if (this.tabItemConfigs) {
      return this.tabItemConfigs.filter(x => !x.isHide);
    } else {
      return [];
    }
  }
  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];
  isAuthorized = true;

  ngOnInit() {
    this.tabItemConfigs = this.componentData.extends.tabItemConfigs;
    this.tagCondition();
    this.checkDom();
  }

  tagCondition() {
    if (!this.tabItemConfigs) return;
    for (const item of this.tabItemConfigs) {
      if (item.condition) {
        const result = compareDataField(this.dataModel, item.condition);
        item.isHide = !result;
      }
    }
  }

  checkDom() {
    if (!this.tabItemConfigs) return;
    const list = this.tabItemConfigs.filter(x => !x.isHide);
    this.tabClick(list[0]);
  }

  ngAfterViewInit() {
    setTimeout(() => {
      const authData = this.setAuthorityData();
      this.zeprideAuthorityData = {
        ...authData,
        afterChecked: this.afterAuthChecked.bind(this)
      };
    }, 0);
    this.registerModelChange();
  }

  tabClick(tabItem?: ITabItemConfig) {
    if (!this.isAuthorized) {
      return;
    }
    this.tabItemConfigs.forEach(x => x.selected = false);
    if (tabItem) { tabItem.selected = true; }
    const doms = document.querySelectorAll('[data-template-id]');
    const domList: any[] = Array.prototype.slice.call(doms);
    domList.map((ele: HTMLElement) => {
      const has = this.tabItemConfigs.find(n => {
        if (n.templateIds) {
          return n.templateIds.find((m: string) => m === ele.dataset.templateId);
        } else {
          return false;
        }
      });
      if (has) {
        if (
          (
            !this.componentData.invalid &&
            tabItem &&
            !tabItem.isHide &&
            tabItem.templateIds &&
            tabItem.templateIds.find((id: string) => id === ele.dataset.templateId)
          )
        ) {
          ele.style.display = 'block';
        } else {
          ele.style.display = 'none';
        }
      }
    });
  }

  afterAuthChecked(params: {
    permitId: PermitConfigId;
    isAuthorized: boolean;
  }) {
    if (!params.isAuthorized) {
      this.isAuthorized = params.isAuthorized;
    }
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.pipe(
      debounceTime(200)
    ).subscribe(async data => {
      if (data.identifyId !== this.componentData.identifyId) {
        // 判断条件是否发生变更
        this.tagCondition();
        if (!this.componentData.tplInvalid) {
          this.checkDom();
        }
      }
    });
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }

}

interface ITabItemConfig {
  id: string;
  title?: string;
  templateIds?: string[];
  index?: number;
  condition?: Condition;
  selected?: boolean;
  isHide?: boolean;
}

